package org.hibiscus.jdp.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.hibiscus.jdp.app.dbdoc.DataSource;
import org.hibiscus.jdp.app.dbdoc.TableStructureDoc;
import org.hibiscus.jdp.app.dbdoc.TableStructureDocFactory;
import org.hibiscus.jdp.domain.query.TsdCreateQuery;
import org.hibiscus.jdp.service.DBDeSignService;
import org.hibiscus.jdp.utils.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

/**
 * Description：数据库设计业务接口实现类
 *
 * @author rannuo
 * @date 2019/8/11
 */
@Slf4j
@Service
public class DBDeSignServiceImpl implements DBDeSignService {

	@Value("${file.tsd.out-path}")
	private String outFilePath;

	@Override
	public String createTableStructureDocument(TsdCreateQuery tsdCreateQuery) {
		TableStructureDoc tableStructureDoc = TableStructureDocFactory.getTableStructureDoc(tsdCreateQuery.getDbType());
		if (tableStructureDoc == null) {
			throw new RuntimeException("解析不到正确的DB类型，操作失败！");
		}

		DataSource dataSource = new DataSource();
		dataSource.setHost(tsdCreateQuery.getHost());
		dataSource.setTableSchema(tsdCreateQuery.getTableSchema());
		dataSource.setUsername(tsdCreateQuery.getUsername());
		dataSource.setPassword(tsdCreateQuery.getPassword());

		String fileName = tableStructureDoc.createDocument(dataSource, outFilePath);
		log.info("创建表结构文档成功，fileName={}", fileName);
		return fileName;
	}

	@Override
	public byte[] downloadTableStructureDocument(String fileName) {
		File file = new File(outFilePath + fileName);
		if (!file.exists()) {
			throw new RuntimeException("文件名称有误，未找到对应文件！fileName=" + fileName);
		}
		byte[] fileBytes = null;
		try {
			fileBytes = IOUtils.getFileBytes(file);
		} catch (IOException e) {
			log.error("从文件获取字节数据异常", e);
		}
		return fileBytes;
	}

}
